package com.syh.app.basic.views;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;

import com.syh.app.basic.R;
import com.syh.app.basic.utils.AppUtil;
import com.syh.app.basic.utils.ComUtil;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 创建者：SYH
 * 时间：2019/9/29 23:04
 * 编辑者：SYH、
 * 补充说明：
 */
public class LoadingDialog extends Dialog {

    private Map<Long, String> mTags = new ConcurrentHashMap<>();
    private WindowManager.LayoutParams mLayoutParams;
    private Context mContext;

    public LoadingDialog(@NonNull Context context) {
        super(context, R.style.TransparentBackgroundDialog);
        mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initContentView();
        init();
    }

    protected void init() {
        Window window = this.getWindow();
        this.mLayoutParams = window.getAttributes();
        if (this.mLayoutParams != null) {
            this.mLayoutParams.height = AppUtil.getScreenHeight(mContext);
            this.mLayoutParams.width = -1;
            this.mLayoutParams.gravity = 17;
        }
        window.setAttributes(this.mLayoutParams);
    }

    protected void initContentView() {
        View dialogView = LayoutInflater.from(this.getContext()).inflate(R.layout.dialog_gif_loading, (ViewGroup) null);
        this.setContentView(dialogView);
        this.setCanceledOnTouchOutside(false);
    }

    public void showDialog(String tag) {
        mTags.put(System.currentTimeMillis(), tag);
        if (!this.isShowing()) {
            show();
        }
    }

    public void hideDialog(String tag) {
        Iterator<Map.Entry<Long, String>> it = mTags.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Long, String> entry = it.next();
            if (entry.getValue().equals(tag)) {
                it.remove();//使用迭代器的remove()方法删除元素
            }
        }
        if (mTags.size() == 0 && this.isShowing()) {
            this.cancel();
        }
    }

}
